/**
 * @file 
 */

#include "barista/il_image_plugin.hpp"

#include <IL/il.h>
#include <IL/ilu.h>

using namespace mocha;
using namespace mocha::graphics;

namespace barista {
il_image_plugin::il_image_plugin(mocha_plugin_object_params* op): op_(op), image_id_(0) {
}
il_image_plugin::il_image_plugin(const il_image_plugin& other): op_(other.op_), image_id_(0) {
	generate();
	bind();
	ilCopyImage(other.image_id_);
}
il_image_plugin::~il_image_plugin() {
	il_image_plugin::free();
}
std::int32_t il_image_plugin::load(const boost::filesystem::path& file) {
	generate();
	bind();
	return IL_FALSE != ilLoadImage(const_cast<char*>(file.string().c_str())); // FIXME: This is a workaround. ilLoadImage should take a const char* in the first place!
}
std::int32_t il_image_plugin::load(std::int8_t* buffer, std::uint32_t size) {
	generate();
	bind();
	return IL_FALSE != ilLoadL(IL_TYPE_UNKNOWN, reinterpret_cast<ILvoid*>(buffer), static_cast<ILuint>(size));
}
std::int32_t il_image_plugin::load(std::int8_t* buffer, std::uint32_t width, std::uint32_t height, const pixel_format& format) {
	return 0;
}
void il_image_plugin::free() {
	if (il_image_plugin::loaded()) {
		ilDeleteImages(1, &image_id_);
	}
}
void il_image_plugin::pixels(std::int8_t*& buffer, std::uint32_t* size) {
	if (il_image_plugin::loaded()) {
		bind();
		buffer = reinterpret_cast<std::int8_t*>(ilGetData());
		*size = 1; // FIXME: Return the actual size of the data! Alternatively, remove the size parameter and require clients to use Mocha's image size functions.
	}
	else {
		*size = 0; // Set size to zero, indicating that there is no data.
	}
}
std::int8_t il_image_plugin::loaded() const {
	return 0 != image_id_;
}
void* il_image_plugin::clone(const void* other) {
	return new il_image_plugin(*reinterpret_cast<const il_image_plugin*>(other)); // The default create function simply uses operator new, so we should do the same here.
}
void il_image_plugin::generate() {
	il_image_plugin::free();
	ilGenImages(1, &image_id_);
}
void il_image_plugin::bind() const {
	ilBindImage(image_id_);
}
}

